package routers

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/ethereum/go-ethereum/log"
	"io/ioutil"
	"net/http"
	"time"

)

func encRespon(data interface{}) []byte {
	responb, err := json.Marshal(data)
	if err != nil {
		log.Warn("encode response", "err", err)
	}
	return responb
}

//callbackResult return  result after callback
type callbackResult struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

//CallbackResponse post callback result to backend.
func CallbackResponse(url string, res interface{}) {
	var repeat = 50
	var waitTime = 2 * time.Minute
	for i := 0; i < repeat; i++ {
		if err := postCallback(url, res); err != nil {
			log.Warn("postcallback", "url", url, "err", err)
			time.Sleep(waitTime)
			continue
		}
		break
	}
}

func postCallback(url string, res interface{}) error {
	//encode result
	responb := encRespon(res)

	//post result to callback url
	r, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer(responb))
	if err != nil {
		log.Warn("chainRespon", "POST err", err)
		return err
	}
	//read callback result
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warn("chainRespon", "Post err", err)
		return err
	}
	defer r.Body.Close()

	//parse response
	result := new(callbackResult)
	if err = json.Unmarshal(b, result); err != nil {
		log.Warn("chainRespon", "Parse err", err)
		return err
	}

	//checkout response
	if result.Code != 0 {
		log.Warn("chainRespon", "err", "post error")
		return errors.New("Post error")
	}

	return nil
}
